package tothreedesignmodel.singleton;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 破坏单例--实例
 *
 * @Author lzhphantom
 * @Description
 * @Date 创建于 14:09 2020/7/17
 * @Modified
 */
public class SingletonBroken {
    /**
     * 反射破坏实例
     *
     * @param
     * @return void
     * @method reflectBrokenTest
     * @author lzhphantom
     * @date 14:42 2020/7/17
     */
    public static void reflectBrokenTest() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
        LazySingletonMultithreading s1 = LazySingletonMultithreading.getInstance();

        Constructor<LazySingletonMultithreading> constructor = LazySingletonMultithreading.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        LazySingletonMultithreading s2 = constructor.newInstance();

        // 结果：1956725890
        System.out.println(s1.hashCode());
        // 结果：356573597
        System.out.println(s2.hashCode());
    }

    /**
     * 序列号破坏单例
     *
     * @param
     * @return void
     * @method serializableBrokenTest
     * @author lzhphantom
     * @date 14:51 2020/7/17
     */
    public static void serializableBrokenTest() throws IOException, ClassNotFoundException {
        LazySingletonMultithreading instance = LazySingletonMultithreading.getInstance();
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.obj"));
        oos.writeObject(instance);
        oos.flush();
        oos.close();

        FileInputStream fileInputStream = new FileInputStream("test.obj");
        ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
        LazySingletonMultithreading s1 = (LazySingletonMultithreading) inputStream.readObject();
        inputStream.close();
        // 1956725890
        System.out.println(instance.hashCode());
        // 1607521710
        System.out.println(s1.hashCode());
    }

    public static void main(String[] args) {
        try {
            SingletonBroken.reflectBrokenTest();
            SingletonBroken.serializableBrokenTest();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
